package com.bauer.springboot.starter.configuration;

import com.aliyun.openservices.ons.api.bean.ConsumerBean;
import com.aliyun.openservices.ons.api.bean.ProducerBean;
import com.bauer.springboot.starter.context.AliMQSubUtils;
import com.bauer.springboot.starter.inerface.AliMQProducer;
import com.bauer.springboot.starter.inerface.impl.DefaultAliProducerImpl;
import com.bauer.springboot.starter.props.AliMQProperties;
import java.util.Properties;
import org.springframework.boot.autoconfigure.condition.ConditionalOnClass;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.Bean;

/**
 * @description:
 * @author: weirui
 * @create: 2020-01-16 16:43
 **/
@EnableConfigurationProperties(AliMQProperties.class)
@ConditionalOnClass(value = {ProducerBean.class})
public class AliMqAutoConfiguration {

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public ProducerBean getProducer(AliMQProperties aliMQProperties) {
        ProducerBean producerBean = new ProducerBean();
        Properties properties = new Properties();
        properties.setProperty("AccessKey", aliMQProperties.getAccessKey());
        properties.setProperty("SecretKey", aliMQProperties.getSecretKey());
        properties.setProperty("GROUP_ID", aliMQProperties.getGroupId());
        producerBean.setProperties(properties);
        return producerBean;
    }


    @Bean
    @ConditionalOnMissingBean(value = {AliMQProducer.class})
    public AliMQProducer producer(AliMQProperties aliMQProperties, ProducerBean producerBean) {
        AliMQProducer aliProducer = new DefaultAliProducerImpl(aliMQProperties, producerBean);
        return aliProducer;
    }

    @Bean(initMethod = "start", destroyMethod = "shutdown")
    @ConditionalOnMissingBean
    public ConsumerBean getConsumer(ApplicationContext applicationContext, AliMQProperties aliMQProperties) {
        ConsumerBean consumerBean = new ConsumerBean();
        Properties properties = new Properties();
        properties.setProperty("GROUP_ID", aliMQProperties.getGroupId());
        properties.setProperty("AccessKey", aliMQProperties.getAccessKey());
        properties.setProperty("SecretKey", aliMQProperties.getSecretKey());
        consumerBean.setProperties(properties);
        consumerBean.setSubscriptionTable(AliMQSubUtils.getSubscription(applicationContext));
        return consumerBean;
    }

}
